<?php 
namespace socket;

include_once 'Gravatar.php';
include_once 'Base.php';

class Message extends Base
{
	private $ser;
	
	private $req;
	
	private $data;
	
	public function __construct($ser,$req)
	{
		parent::__construct();
		$this->ser = $ser;
		$this->req = $req;
		$this->data = json_decode($this->req->data);
		switch ($this->data->code){
			case 1:    //用户登录
				$this->loginRoom();
				break;
			case 3:  //大厅聊天
				$this->roomChat($this->data);
				break;
		}
	}
	
	/**
	 * 登录聊天室
	 */
	public function loginRoom()
	{
		//登录成功返回用户数据到客户端
		$this->data->user_head = Gravatar::getGravatar($this->data->email);
		$this->data->fd = $this->req->fd;
		$this -> ser ->push($this->req -> fd , json_encode($this -> data));
		//给所有在线用户广播信息，通知上线
		$notice = $this->data;
		$notice -> code = 2;
		$redis_str = $this->redis->get('user_list');
		if($redis_str) {
			$redis_arr = json_decode($redis_str,true);
			$redis_arr[] = $this->data;
			$this->redis->set('user_list',json_encode($redis_arr));
		}else{
			$this->redis->set('user_list',json_encode([$this->data]));
		}
		$user_list = json_decode($this->redis->get('user_list'),true);
		//遍历数组给对象发送消息
		$list = [
				'code' => 2,
				'user_list' => $user_list,
				'notice' => $notice
		];
		$this->roomChat($list);
	}
	
	/**
	 * 聊天室全局广播
	 */
	public function roomChat($list)
	{
		$user_list = json_decode($this->redis->get('user_list'),true);
		//遍历数组给对象发送消息
		foreach ($user_list as $val) {
			$this->ser -> push($val['fd'],json_encode($list));
		}
	}
}